package com.duoduo.demo.springnoxml;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;

import com.duoduo.system.security.MyFilterSecurityInterceptor;
import com.duoduo.system.service.UserService;

/**
 * 可以参考https://stackoverflow.com/questions/33480364/warn-o-s-web-servlet-pagenotfound-no-mapping-found-for-http-request-with-uri
 * @author chengesheng@kedacom.com
 * @date 2017年11月3日下午5:27:37
 */
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

	@Autowired
	private MyFilterSecurityInterceptor myFilterSecurityInterceptor;

	@Bean
	public UserDetailsService userDetailsService() { // 注册UserDetailsService 的bean
		return new UserService();
	}

	@Override
	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
		auth.userDetailsService(userDetailsService()); // user Details Service验证

	}

	/**
	 * 设置范例
	 * 
	 * <pre>
	 * http.authorizeRequests().anyRequest().authenticated().and().formLogin().loginPage("/login")
	 * 		// 设置默认登录成功跳转页面
	 * 		.defaultSuccessUrl("/index").failureUrl("/login?error").permitAll().and()
	 * 		// 开启cookie保存用户数据
	 * 		.rememberMe()
	 * 		// 设置cookie有效期
	 * 		.tokenValiditySeconds(60 * 60 * 24 * 7)
	 * 		// 设置cookie的私钥
	 * 		.key("").and().logout()
	 * 		// 默认注销行为为logout，可以通过下面的方式来修改
	 * 		.logoutUrl("/custom-logout")
	 * 		// 设置注销成功后跳转页面，默认是跳转到登录页面
	 * 		.logoutSuccessUrl("").permitAll();
	 * </pre>
	 */
	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.authorizeRequests().anyRequest().authenticated() // 任何请求,登录后可以访问
				.and().formLogin().loginPage("/login").failureUrl("/login?error").permitAll() // 登录页面用户任意访问
				.and().logout().permitAll(); // 注销行为任意访问
		http.addFilterBefore(myFilterSecurityInterceptor, FilterSecurityInterceptor.class);
	}
}
